import { Component } from 'react'
import router from 'umi/router'
import { RouteComponentProps } from 'react-router'
import { Mutation, Query } from 'react-apollo'
import { gql } from 'apollo-boost'
import { Button, Icon, Popconfirm } from 'antd'
import { DELETE_USER } from './$id'
import { User } from './type'
import UserTable from './components/table'

interface Props extends RouteComponentProps<never> {}

export default class UserPage extends Component<Props> {
  key = 'allUsers'
  path = '/users'

  state = {
    selected: [] as User[],
  }

  onPaginationChange = (page: number, perpage?: number) =>
    router.push({
      pathname: this.path,
      query: {
        page: page !== 1 ? page : undefined,
        perpage: perpage !== 10 ? perpage : undefined,
      },
    })

  render = () =>
    ((
      {
        location: {
          query: { page = 1, perpage = 10 },
        },
      },
      { key, path },
    ) => (
      <Query
        query={QUERY_USERS}
        fetchPolicy="network-only"
        variables={{
          skip: (+page - 1) * +perpage,
          first: +perpage,
          orderBy: 'updatedAt_DESC',
        }}
      >
        {({ loading, data, refetch }) => (
          <Mutation mutation={DELETE_USER}>
            {deletes => (
              <div>
                <Operations
                  selected={this.state.selected}
                  onCreate={() => router.push(path + '/+?edit=1')}
                  onDeleteSelected={async () => {
                    await Promise.all(
                      this.state.selected.map(({ id }) =>
                        deletes({ variables: { id } }),
                      ),
                    )
                    this.setState({ selected: [] })
                    await refetch()
                  }}
                />
                <UserTable
                  loading={loading}
                  data={(data && data[key]) || []}
                  link={id => path + '/' + id}
                  onEdit={id => router.push(path + '/' + id + '?edit=1')}
                  onDelete={async id => {
                    await deletes({ variables: { id } })
                    await refetch()
                  }}
                  rowSelection={{
                    onChange: (_, selected) => this.setState({ selected }),
                  }}
                  pagination={{
                    current: +page,
                    pageSize: +perpage,
                    total:
                      data &&
                      data[`_${key}Meta`] &&
                      data[`_${key}Meta`]['count'],
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onShowSizeChange: this.onPaginationChange,
                    onChange: this.onPaginationChange,
                  }}
                />
              </div>
            )}
          </Mutation>
        )}
      </Query>
    ))(this.props, this)
}

interface OperationsProps {
  selected: User[]
  onCreate: () => void
  onDeleteSelected: () => void
}

const Operations = ({
  selected,
  onCreate,
  onDeleteSelected,
}: OperationsProps) => (
  <div style={{ marginBottom: '20px' }}>
    <Button onClick={onCreate}>
      <Icon type="plus" />
      Create
    </Button>
    {selected.length > 0 && (
      <span>
        <span style={{ margin: '9px' }} />
        <Popconfirm title="Are you sure?" onConfirm={onDeleteSelected}>
          <Button>Delete selected {selected.length} users</Button>
        </Popconfirm>
      </span>
    )}
  </div>
)

export const QUERY_USERS = gql`
  query($skip: Int, $first: Int, $last: Int, $orderBy: UserOrderBy) {
    allUsers(skip: $skip, first: $first, last: $last, orderBy: $orderBy) {
      id
      username
      name
      role
      createdAt
      updatedAt
    }
    _allUsersMeta {
      count
    }
  }
`
